//相关业务逻辑
$(function () {
  page.initData();
  page.bind();
  page.getUserName();
});


var page = { //页面总变量
  isMenuAction: false,
  lockStatus: false,
  $lockBtn: null,

  initData: function () {
    var lockStatus = window.localStorage.getItem('lockStatus');
    if (lockStatus === null) {
      lockStatus = false;
    } else {
      lockStatus = eval(lockStatus);
    }
    this.lockStatus = lockStatus;
    this.changeLockStatus();
  },

  bind: function () {
    $("#upPassword").bind("click", function () {
      var pass1 = $("#alterPasswordForm-password").val();
      var pass2 = $("#alterPasswordForm-newPassword").val();
      var pass3 = $("#alterPasswordForm-newPasswordCheck").val();
      if (pass1 == '') {
        $("#alterPasswordForm-password").attr("placeholder", "请输入密码");
        return false;
      }
      if (pass2 == '') {
        $("#alterPasswordForm-newPassword").attr("placeholder", "请输入新密码");
        return false;
      }
      if (pass3 == '') {
        $("#alterPasswordForm-newPasswordCheck").attr("placeholder", "请再次新输入密码");
        return false;
      }
      var sendData = {
        'password': pass2
      }
      ajaxUtil.ajaxRuquest('user/updatePassword', sendData, function (data) {
        layer.msg(data, {
          icon: 1
        });
        $("#modal-demo2").modal("hide");
      });
    });

    $("#alterPasswordForm-password").bind("change", function () {
      var pass = $(this).val();
      if (pass == '') {
        $("#alterPasswordForm-password").attr("placeholder", "请输入密码");
        return false;
      }
      var sendData = {
        'password': pass
      }
      ajaxUtil.ajaxRuquest('user/jiaoYanPass', sendData, function (data) {
        if (!data) {
          $("#alterPasswordForm-password").val("");
          $("#alterPasswordForm-password").attr("placeholder", "输入的密码不正确");
        }
      });
    });

    $("#alterPasswordForm-newPassword").bind("change", function () {
      var pass = $(this).val();
      if (pass == '') {
        $("#alterPasswordForm-newPassword").attr("placeholder", "请输入新密码");
        return false;
      }
    });

    $("#alterPasswordForm-newPasswordCheck").bind("change", function () {
      var newpass = $(this).val();
      if (newpass == '') {
        $("#alterPasswordForm-newPasswordCheck").attr("placeholder", "请再次输入新密码");
        return false;
      }
      var pass = $("#alterPasswordForm-newPassword").val();
      if (newpass != pass) {
        $("#alterPasswordForm-newPasswordCheck").val("");
        $("#alterPasswordForm-newPasswordCheck").attr("placeholder", "两次输入密码不匹配");
        return false;
      }
    });

    $("#loginOut").bind("click", function () {
      window.localStorage.setItem('password', "");
      location.href = "user/loginOut";
    });

    $('#leftSideMenu .menu_dropdown').on('click', '.menu-article dd li>a', function () {
      page.closeMenu();
    });

    $('#dislpayArrow').on('mouseover', this.toShowMenu);

    $("#sysInfo").unbind("click");
    $("#sysInfo").bind("click", function () {
      var userAgent = window.navigator.userAgent;
      if (userAgent.indexOf('WOW') < 0 && userAgent.indexOf("Edge") < 0) {
        isChrome = true;
        /*broName = 'Chrome浏览器';*/
        strStart = userAgent.indexOf('Chrome');
        strStop = userAgent.indexOf(' Safari');
        temp = userAgent.substring(strStart, strStop);
        broName = temp.replace('/', '版本号');
        $.Huimodalalert('当前使用的浏览器<br/>' + broName, 5000);
      }
    })

    $('.lock-menu').click('click', function () {
      var lockStatus = page.lockStatus;
      lockStatus = !lockStatus;
      page.lockStatus = lockStatus;
      window.localStorage.setItem('lockStatus', lockStatus);
      page.changeLockStatus();
    });
  },

  toShowMenu: function () {
    var totalWidth = $('body').width();
    if (totalWidth <= 767) {
      return;
    }

    var $arrow = $('#dislpayArrow');
    if (!$arrow.hasClass('open')) {
      return;
    }

    page.openMenu();
  },

  getUserName: function () {
    var self = this;
    SystemUtil.getLoginUser().then(function (user) {
      var $iframe = $('#welcome_iframe iframe');
      if ($iframe.length === 0) {
        // $('#welcome_iframe').append('<iframe scrolling="yes" frameborder="0" src="shoppingMallMgr/releasedMaterial/index.html"></iframe>');
        $('#welcome_iframe').append('<iframe scrolling="yes" frameborder="0" src="welcome.html"></iframe>');
      }
      $("#loginUserNameA").text(user.userName);
      $(".companyName").text(user.company);
      $("title").html(user.company);

      // if (!self.checkTimeExpire(user)) {
      //   return;
      // }

      var pageList = user.pageList;
      if (pageList === undefined || pageList.length === 0) {
        return;
      }

      var $menuHtml = self.getMenuHtml(pageList, user);
      $('#leftSideMenu .menu_dropdown').html($menuHtml.html());
      $.Huifold(".menu_dropdown dl dt", ".menu_dropdown dl dd", "fast", 1, "click");
      page.closeMenu();
    }).catch(function () {
      location.href = "login.html";
    });
  },

  checkTimeExpire: function (user) {
    var companyInfo = user.companyInfo;
    var endTime = companyInfo.endTime;
    var clockTime = companyInfo.clockTime;

    if (endTime === null || clockTime === null) {
      return true;
    }
    if (moment().isSameOrAfter(endTime, 'day')) {
      layer.alert('时间已到期，请去续费', {
        end: function () {
          location.href = "login.html";
        }
      });
      return false;
    }

    var companyId = user.companyId;
    if (moment().isSameOrAfter(clockTime, 'day')) {
      var clockTimeData = localStorage.getItem('clockTimeData');
      if (clockTimeData === null) {
        clockTimeData = {};
      } else {
        clockTimeData = JSON.parse(clockTimeData);
      }

      var time = clockTimeData[companyId];
      if (time === undefined) {
        time = null;
      }

      var flag = true;
      var refrehTime = true;
      if (time !== null) {
        if (moment().isSame(time, 'day')) {
          var rangeTime = moment().diff(time, 'minute', true);
          if (rangeTime > 5) {
            flag = false;
          }
          refrehTime = false;
        }
      }

      if (flag) {
        var msg = `到期时间:${moment(endTime).format('YYYY-MM-DD')}`;
        $('.clock-time').html(msg);
        $('.clock-time').show();
        this.setHideRunning(time);
      } else {
        $('.clock-time').remove();
      }

      if (refrehTime) {
        var now = moment().valueOf();
        clockTimeData[companyId] = now;
        localStorage.setItem('clockTimeData', JSON.stringify(clockTimeData));
      }
    } else {
      var clockTimeData = localStorage.getItem('clockTimeData');
      $('.clock-time').remove();
      if (clockTimeData !== null) {
        clockTimeData = JSON.parse(clockTimeData);
        if (clockTimeData[companyId] !== undefined) {
          delete clockTimeData[companyId];
          if (SystemUtil.isEmptyObject(clockTimeData)) {
            localStorage.removeItem('clockTimeData');
          } else {
            localStorage.setItem('clockTimeData', JSON.stringify(clockTimeData));
          }
        }
      }
    }
    return true;
  },

  setHideRunning: function (time) {
    var rangeTime;
    if (time === null) {
      rangeTime = 5 * 60 * 1000;
    } else {
      rangeTime = moment().diff(time);
      rangeTime = 5 * 60 * 1000 - rangeTime;
    }
    if (rangeTime < 0) {
      return;
    }

    setTimeout(function () {
      $('.clock-time').remove();
    }, rangeTime);
  },

  getMenuHtml: function (pageList, user) {
    var menus = MenuUtil.getAuthorityMenus(pageList, user);
    var $menuDiv = $('<div></div>');
    for (var i = 0; i < menus.length; i++) {
      var menu = menus[i];
      var $menu = $('<dl class="menu-article"></dl>');
      var $menuHead = /*html*/ `
        <dt>
          <i class="Hui-iconfont">${menu.icon}</i>
          <span class="leftFont">${menu.title}</span>
          <i class="Hui-iconfont menu_dropdown-arrow">&#xe6d5;</i>
        </dt>
      `;
      $menu.append($menuHead);

      var subMenus = menu.subMenus;
      var $subMenus = $('<ul></ul>');
      for (var j = 0; j < subMenus.length; j++) {
        var subMenu = subMenus[j];
        var jumpUrl = subMenu.jumpUrl;
        if (jumpUrl === undefined) {
          jumpUrl = subMenu.url;
        }

        var url = `${subMenu.prefix===undefined?'':subMenu.prefix}${jumpUrl}`;
        var showTitle = subMenu.showTitle;
        var title = subMenu.title;
        if (showTitle === undefined) {
          showTitle = title;
        }

        var $subMenu = /*html*/ `
          <li ${subMenu.hidden?'hidden':''}>
            <a data-href="${url}" data-title="${title}" href="javascript:void(0)" class="leftFontLi">${showTitle}</a>
          </li>
        `;
        $subMenus.append($subMenu);
      }
      $menu.append($('<dd></dd>').append($subMenus));

      $menuDiv.append($menu);
    }
    return $menuDiv;
  },

  closeMenu: function () {
    if (page.lockStatus) {
      return;
    }
    if (page.isMenuAction) {
      return;
    }

    $("#dislpayArrow").addClass("open");
    $("body").addClass("big-page");
    page.isMenuAction = true;
    setTimeout(function () {
      page.isMenuAction = false;
    }, 250);
  },

  openMenu: function () {
    if (page.isMenuAction) {
      return;
    }

    $("#dislpayArrow").removeClass("open");
    $("body").removeClass("big-page");
    page.isMenuAction = true;
    setTimeout(function () {
      page.isMenuAction = false;
    }, 250);
  },

  changeLockStatus: function () {
    var lockStatus = page.lockStatus;
    var $lockMenu = $('.lock-menu');
    if (lockStatus) {
      $lockMenu.addClass('open-lock');
      $lockMenu.attr('title', '取消锁定菜单');
    } else {
      $lockMenu.removeClass('open-lock');
      $lockMenu.attr('title', '锁定菜单');
    }
  }
}
